package org.example.udf;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.util.Collector;


import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * 自定义表聚合函数（多进多出）,最分组的TOP2
 */
public class MyTableAggregateFunctionDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //分数、权重
        DataStreamSource<Integer> numDS = env.fromElements(3, 6, 12, 5, 8, 9, 4);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        //指定字段
        Table numTable = tableEnv.fromDataStream(numDS, $("num"));
        //注册函数
        tableEnv.createTemporarySystemFunction("Top2", Top2Function.class);

        numTable.flatAggregate(call("Top2", $("num")).as("value", "rank"))
                .select($("value"), $("rank"))
                .execute()
                .print();

    }

    //泛型：返回值类型：<数值、排名>，(12,1),(9,2)
    //累加值类型：<第一大的数，第二大的数> (12,9)
    public static class Top2Function extends TableAggregateFunction<Tuple2<Integer, Integer>, Tuple2<Integer, Integer>> {


        @Override
        public Tuple2<Integer, Integer> createAccumulator() {
            return Tuple2.of(0, 0);
        }


        /**
         * 每来一次，比较一次大小，更新到累加器中
         *
         * @param acc
         * @param num
         */
        public void accumulate(Tuple2<Integer, Integer> acc, Integer num) {
            if (num > acc.f0) {
                //更新第一，第一退位第二，第二移除
                acc.f1 = acc.f0;
                acc.f0 = num;

            } else if (num > acc.f1) {
                //更新第二位，第二退位
                acc.f1 = num;
            }

        }

        public void emitValue(Tuple2<Integer, Integer> acc, Collector<Tuple2<Integer, Integer>> out) {
            if (acc.f0 != 0) {
                out.collect(Tuple2.of(acc.f0, 1));
            }
            if (acc.f1 != 0) {
                out.collect(Tuple2.of(acc.f1, 2));
            }
        }
    }
}
